
package com.vpen.chat.client;

import com.vpen.chat.client.handler.ChatClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/15 16:30
 */
@Slf4j
public class ChatClient {
    private final String host;
    private final int port;

    private final EventLoopGroup loopGroup;

    private final Bootstrap bootstrap;

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
        this.bootstrap = new Bootstrap();
        this.loopGroup = new NioEventLoopGroup();
    }


    public void run() {
        try {
            this.bootstrap.group(this.loopGroup)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(this.host, this.port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 从channel种获取pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加解码处理器
                            pipeline.addLast("stringDecoder", new StringDecoder());
                            // 添加编码处理器
                            pipeline.addLast("stringEncoder", new StringEncoder());
                            pipeline.addLast("chatClientHandler", new ChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = this.bootstrap.connect().sync();

            Channel channel = channelFuture.channel();
            log.debug("----{}----请输入消息", channel.localAddress());

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                log.debug("请输入");
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg);
            }

//            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            this.loopGroup.shutdownGracefully();
        }

    }


}
